use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::thread;

fn handle_client(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    match stream.read(&mut buffer) {
        Ok(size) => {
            // 将接收到的字节切片转换为字符串（去除可能多余的空字节）
            let request = String::from_utf8_lossy(&buffer[0..size]);
            println!("从客户端接收到消息: {}", request);

            // 构造响应消息
            let response = "Hello, Client! I received your message.";
            stream.write(response.as_bytes()).expect("写入响应到客户端失败");
            println!("已向客户端发送响应");
        }
        Err(e) => {
            println!("读取客户端消息出错: {}", e);
        }
    }
}

fn main() {
    // 监听的本地端口，这里以8080为例，可根据需求修改
    let listener = TcpListener::bind("127.0.0.1:8080").expect("无法绑定到指定地址和端口");
    println!("服务器已启动，正在监听端口 8080...");

    loop {
        match listener.accept() {
            Ok((stream, _)) => {
                println!("客户端已连接");
                // 为每个连接的客户端创建一个新线程来处理通信
                thread::spawn(move || {
                    handle_client(stream);
                });
            }
            Err(e) => {
                println!("接受客户端连接出错: {}", e);
            }
        }
    }
}
